package com.push.xu.xpush.client;

import com.push.xu.xpush.constant.Constant;
import com.push.xu.xpush.core.ZPushClient;
import com.push.xu.xpush.util.SPUtils;
import com.xiaomi.mipush.sdk.MiPushClient;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;

public class XiaomiPushClient implements ZPushClient {
	public static final String MI_PUSH_APP_ID = "MI_PUSH_APP_ID";
	public static final String MI_PUSH_APP_KEY = "MI_PUSH_APP_KEY";

	private String mAppId;
	private String mAppKey;
	private Context mContext;
	private Bundle metaData;

	@Override
	public void initContext(Application application) {
		this.mContext = application.getApplicationContext();
		// 读取小米对应的appId和appSecret
		try {
			metaData = mContext.getPackageManager().getApplicationInfo(mContext.getPackageName(),
					PackageManager.GET_META_DATA).metaData;
			mAppId = metaData.getString(MI_PUSH_APP_ID).trim();
			mAppKey = metaData.getString(MI_PUSH_APP_KEY).trim();
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void register() {
		if (TextUtils.isEmpty(mAppId) || TextUtils.isEmpty(mAppKey)) {
			throw new IllegalArgumentException("xiaomi push appId or appKey is not init,"
					+ "check you AndroidManifest.xml is has MI_PUSH_APP_ID or MI_PUSH_APP_KEY meta-data flag please");
		}
		MiPushClient.registerPush(mContext, mAppId, mAppKey);
	}

	@Override
	public void unRegister() {
        final String token = SPUtils.getInstance(Constant.PUSH_MESSAGE_TABLE).getString("push_token");
		if (!TextUtils.isEmpty(token)) {
			MiPushClient.unregisterPush(mContext);
		}
	}

	@Override
	public void clearNotiById(Context context, int id) {
		MiPushClient.clearNotification(context, id);
	}

	@Override
	public String getRegistration(Context context) {
		return MiPushClient.getRegId(context);
	}

	@Override
	public void bindAlias(String alias) {
		MiPushClient.setAlias(mContext,alias,null);
	}

	@Override
	public void unBindAlias(String alias) {
		MiPushClient.unsetAlias(mContext, alias, null);
	}

	@Override
	public void addTag(String tag) {
		MiPushClient.subscribe(mContext,tag,null);
	}

	@Override
	public void deleteTag(String tag) {
		MiPushClient.unsubscribe(mContext, tag, null);
	}
}
